package com.bsg.upm.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.check.CheckResult;
import com.bsg.upm.check.UserGroupCheck;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.dto.UserDto;
import com.bsg.upm.dto.UserGroupDto;
import com.bsg.upm.dto.UserRoleDto;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.entity.UserGroupEntity;
import com.bsg.upm.entity.UserRoleEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.PrimaryKeyUtils;

/**
 * 用户组管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class UserGroupService extends BaseService {

	@Resource
	private UserService userService;

	@Resource
	private UserRoleService userRoleService;

	@Resource
	private UserGroupCheck userGroupCheck;

	/**
	 * 用户组查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			JSONArray results = new JSONArray();

			// 获取指定条件的用户组
			List<UserGroupEntity> groups = userGroupDao.list(paramMap);

			for (UserGroupEntity group : groups) {
				// 构建用户组展示对象
				UserGroupDto groupDto = buildShowDto(group, false);
				results.add(groupDto);
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("用户组查询异常", e);
			throw new APIException("用户组查询异常:" + e.getMessage());
		}
	}

	/**
	 * 用户组详情
	 * 
	 * @param id
	 *            用户组编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson get(String id) throws APIException {
		try {
			// 获取指定的用户组
			UserGroupEntity group = userGroupDao.get(id);
			if (group == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该用户组不存在");
			}

			// 构建用户组展示对象
			UserGroupDto groupDto = buildShowDto(group, true);

			return RespJsonFactory.buildOK(groupDto);
		} catch (Exception e) {
			logger.error("用户组获取异常", e);
			throw new APIException("用户组获取异常:" + e.getMessage());
		}
	}

	/**
	 * 用户组新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 用户组新增检查
			CheckResult chkRS = userGroupCheck.checkSave(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建组对象
			UserGroupEntity group = buildUserGroup(paramMap);
			userGroupDao.save(group);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_USER_GROUP, operateAcion, group.getId(), group.getName());

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("用户组" + operateAcionText + "异常", e);
			throw new APIException("用户组" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 用户组编辑
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson update(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_UPDATE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 用户组编辑检查
			CheckResult chkRS = userGroupCheck.checkUpdate(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建组对象
			UserGroupEntity group = buildUserGroupToUpdate(paramMap);
			userGroupDao.update(group);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_USER_GROUP, operateAcion, group.getId(), group.getName());

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("用户组" + operateAcionText + "异常", e);
			throw new APIException("用户组" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 用户组删除
	 * 
	 * @param id
	 *            用户组编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String id) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的用户组
			UserGroupEntity group = userGroupDao.get(id);

			// 用户组删除检查
			CheckResult chkRS = userGroupCheck.checkRemove(group);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			userGroupDao.remove(id);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_USER_GROUP, operateAcion, group.getId(), group.getName());

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("用户组" + operateAcionText + "异常", e);
			throw new APIException("用户组" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 构建用户组展示对象
	 * 
	 * @param group
	 *            用户组对象
	 * @param showDetail
	 *            是否展示详情
	 * @return 用户组展示对象
	 */
	private UserGroupDto buildShowDto(UserGroupEntity group, boolean showDetail) {
		UserGroupDto groupDto = buildGroupBaseDto(group);
		List<UserEntity> users = group.getUsers();
		List<UserDto> userDtos = new ArrayList<>(users.size());
		groupDto.setUsers(userDtos);
		
		for (UserEntity user : users) {
			UserDto userDto = userService.buildUserBaseDto(user);
			userDtos.add(userDto);

			UserRoleEntity role = user.getUserRole();
			if (role != null) {
				UserRoleDto roleDto = userRoleService.buildRoleBaseDto(role);
				userDto.setRole(roleDto);
			}
		}
		return groupDto;
	}

	/**
	 * 构建用户组基础展示对象
	 * 
	 * @param group
	 *            用户组对象
	 * @return 用户组基础展示对象
	 */
	public UserGroupDto buildGroupBaseDto(UserGroupEntity group) {
		UserGroupDto groupDto = new UserGroupDto();
		groupDto.setId(group.getId());
		groupDto.setName(group.getName());
		groupDto.setDescription(group.getDescription());
		return groupDto;
	}

	/**
	 * 构建用户组对象
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 用户组
	 */
	private UserGroupEntity buildUserGroup(Map<String, Object> paramMap) {
		UserGroupEntity group = new UserGroupEntity();
		group.setId(PrimaryKeyUtils.uniqueId());
		group.setName(StringUtils.trim((String) paramMap.get("name")));
		group.setDescription(StringUtils.trim((String) paramMap.get("description")));
		return group;
	}

	/**
	 * 构建用户组对象用于更新操作
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 用户组
	 */
	private UserGroupEntity buildUserGroupToUpdate(Map<String, Object> paramMap) {
		// 获取指定的用户组
		UserGroupEntity group = userGroupDao.get((String) paramMap.get("id"));
		if (paramMap.containsKey("name")) {
			group.setName(StringUtils.trim((String) paramMap.get("name")));
		}

		if (paramMap.containsKey("description")) {
			group.setDescription(StringUtils.trim((String) paramMap.get("description")));
		}
		return group;
	}

}
